/*
 *  src/mm/ff.c
 *
 *  Harry Wei <harryxiyou@gmail.com> (C) 2011
 */
#include <glib.h>

#include "mm.h"

int mm_ff(struct mm_ctrl *ctrl, uint32_t size)
{
	g_message("enter func %s...", __func__);
	int ret = 0;
	if (ctrl->free_size == ctrl->free_head->size) {
		ctrl->free_head->size -= size;
		ctrl->free_head->start_addr += size + 1;
		return ctrl->start_addr;
	}
	g_message("%s -- 77 dbg %p", __func__, ctrl);
	struct free_section *tmp1 = NULL;
	struct free_section *tmp2 = NULL;
	tmp1 = ctrl->free_head;
	tmp2 = tmp1->next;
	if (tmp1->size == size) {
		ctrl->free_head = tmp2;
		g_free(tmp1);
		return tmp1->start_addr;
	} 
	if (tmp1->size > size) {
		tmp1->size -= size;
		tmp1->start_addr += size + 1;
		return tmp1->start_addr;
	}
	while (1) {
		if (tmp2->size == size) {
			ret = tmp2->start_addr;
			tmp1->next = tmp2->next;
			g_free(tmp2);
			return ret;
		} 
		if (tmp2->size > size) {
			tmp2->size -= size;
			tmp2->start_addr += size + 1;
			return tmp2->start_addr;
		}
		if (NULL == tmp2->next) {
			g_message("%s -- no enough memory!", __func__);
			break;
		}
		tmp1 = tmp1->next;
		tmp2 = tmp1->next;
	}
	g_message("leave func %s", __func__);
	return -1;
}
